#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int semiOrderedPermutation(vector<int>& nums) {
        int n = nums.size();
        int left = 0, right = n - 1;
        for (int i = 0; i < n; i++) if (nums[i] == n) right = i; else if (nums[i] == 1) left = i;
        int res = n - right - 1 + left;
        if (right < left) res -= 1;
        return res;
    }
};